const moment = require('moment');
const conn = require('../db/db.js');
const marked = require('marked');

// -----------------------------------------------渲染页面----------------------------------------------

const showAdd = (req,res) => {
    // 如果沒有登录跳转到登录页面
    if(!req.session.islogin) return res.redirect('/login');
    // 渲染页面时添加进数据进页面
    res.render('./article/add.ejs',{user:req.session.user,islogin:req.session.islogin});
}

const showInfo = (req,res) => {
    let sql = 'select * from blog_articles where id = ?';
    let id = req.params.id;
    conn.query(sql,id,(err,result) => {
        // console.log(result)
        if(err) return res.redirect('/');
        if(result.length != 1) return res.send({status:500,msg:'查询错误'});
        // 将markdown文本 转换为 html文本
        let html = marked(result[0].content);
        result[0].content = html;
        res.render('./article/info.ejs',{
            user:req.session.user,
            islogin:req.session.islogin,
            article:result[0]
        });
    })   
}

const showEdit = (req,res) => {
    // console.log(res);
    let id = req.params.id;
    let sql = 'select * from blog_articles where id = ?';
    conn.query(sql,id,(err,result) => {
        if(err) return res.redirect('/article/info');
        if(result.length != 1) return res.send({status:501,msg:'查询错误'});
        res.render('./article/edit.ejs',{user:req.session.user,islogin:req.session.islogin,article:result[0]});
    })
    
}

// -----------------------------------------------数据库 页面交互----------------------------------------------

const addArticle = (req,res) => {
    // console.log(req.body);
    let article = req.body;
    article.ctime = moment().format('YYYY-MM-DD HH:mm:ss');
    let sql = 'insert into blog_articles set ?';
    conn.query(sql,article,(err,result) => {
        console.log(result);
        if(err) return res.send({status:501,msg:'添加失败' + err.message});
        if(result.affectedRows != 1) return res.send({status:502,msg:'添加错误'});
        res.send({status:200,msg:'success',insertId:result.insertId});
    })
}

const editArticle = (req,res) => {
    // console.log(req.body);
    let sql = 'update blog_articles set ? where id = ?';
    let article = req.body;
    conn.query(sql,[article,article.id],(err,result) => {
        if(err) return res.send({status:501,msg:'修改失败' + err.message});
        res.send({status:200,msg:'success'});
    })
}

module.exports = {
    showAdd,
    addArticle,
    showInfo,
    showEdit,
    editArticle
}